package com.sencorsta.ids.talk.OpenHandler;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.protobuf.InvalidProtocolBufferException;
import com.sencorsta.ids.common.information.ErrorCodeList;
import com.sencorsta.ids.common.proto.utils.ReturnUtils;
import com.sencorsta.ids.common.service.MysqlService;
import com.sencorsta.ids.common.service.RedisService;
import com.sencorsta.ids.core.entity.ClientEvent;
import com.sencorsta.ids.core.log.Out;
import com.sencorsta.ids.core.tcp.opensocket.OpenMessageHandler;
import com.sencorsta.ids.core.tcp.socket.protocol.RpcMessage;
import com.sencorsta.ids.talk.proto.ImtalkSearchFriendsByProto;
import io.netty.channel.Channel;

/**
* @description: 搜索好友
* @author TAO
* @date 2019/6/18 17:40
*/

@ClientEvent("SearchFriend")
public class SearchFriendsHandler extends OpenMessageHandler implements RedisService {
    @Override
    public RpcMessage request(Channel channel, JSONObject json, String content, byte[] data, byte[] protobuf) {
        Out.debug("---------------------------搜索好友SearchFriend--------------------------------");
        //创建搜索好友的Proto的res返回前端的对象
        ImtalkSearchFriendsByProto.SearchMessageRes.Builder res=ImtalkSearchFriendsByProto.SearchMessageRes.newBuilder();
        try{
            //创建搜索好友的Proto的req接收前端数据的对象
            ImtalkSearchFriendsByProto.SearchMessageReq req=ImtalkSearchFriendsByProto.SearchMessageReq.parseFrom(protobuf);
            res.setSign(req.getSign());//返回前端标识信息
            //获取目标用户id
            String TagCondition=req.getTagCondition();//搜索的用户昵称/手机号码

            //TODO 搜索优化
            JSONArray array=null;
            {
                String sql="SELECT `UUID` FROM `account` WHERE `phone`=?";
                Object[] args=new Object[]{
                        TagCondition
                };
                array= MysqlService.getInstance().select(sql,args);
            }

            if (array.size()!=0){//原array!=null
                //搜索目标用户信息
                Out.debug("UUID==>",String.valueOf(array.get(0)));
                JSONObject jsz=JSONObject.parseObject(String.valueOf(array.get(0)));
                JSONObject result=JSONObject.parseObject(R_ACCOUNT.hget(ACCOUNT,jsz.getString("UUID")));
                Out.debug("userId==>",result.getString("userId"));
                res.setUserId(result.getString("userId"));
            }else{//为空  手机号码/昵称
                Out.debug("---------------没有找到账号----------------------");
                res.setMsg(ReturnUtils.ErrorProto(ErrorCodeList.LOGIN_ACC_NOT_FIND));
                return responseProto(res);
            }
            res.setMsg(ReturnUtils.ErrorProto(ErrorCodeList.SUCCESS));
            return responseProto(res);
        }catch (InvalidProtocolBufferException e){
            e.printStackTrace();
            return responseProto(res.setMsg(ReturnUtils.ErrorProto(ErrorCodeList.SERVER_ERROR)));
        }
    }

}
